//
//  CommonListCoordinator.m
//  BaseProject
//
//  Created by itzhaolei on 2024/5/15.
//

#import "CommonListCoordinator.h"
#import "CommonSectionController.h"
#import "CommonSectionAdapter.h"

@interface CommonListCoordinator()<IGListAdapterDataSource>

{
    IGListAdapter *_adapter;
}

/// 控制器
@property (nonatomic, weak) UIViewController <CoordinatorDataSource> *delegate;

@end

@implementation CommonListCoordinator

- (instancetype)initWithDelegate:(__weak UIViewController <CoordinatorDataSource> *)delegate {
    if (self = [super init]) {
        self.delegate = delegate;
    }
    return self;
}

#pragma mark - Lazy
- (IGListAdapter *)adapter {
    if (!_adapter) {
        IGListAdapter *adapter = [[IGListAdapter alloc] initWithUpdater:[[IGListAdapterUpdater alloc] init] viewController:self.delegate workingRangeSize:0];
        adapter.dataSource = self;
        _adapter = adapter;
    }
    return _adapter;
}

#pragma mark - IGListAdapterDataSource
// 适配器管理的区域对应的模型
- (NSArray<id <IGListDiffable>> *)objectsForListAdapter:(IGListAdapter *)listAdapter {
    NSArray<CommonSectionAdapter *> *sectionAdapters = [self.delegate objectsForListAdapter:listAdapter];
    for (CommonSectionAdapter *sectionAdapter in sectionAdapters) {
        sectionAdapter.section = [sectionAdapters indexOfObject:sectionAdapter];
    }
    return (NSArray<id <IGListDiffable>> *)sectionAdapters;
}
// 根据object，加载指定区域的SectionController
- (IGListSectionController *)listAdapter:(IGListAdapter *)listAdapter sectionControllerForObject:(id)object {
    CommonSectionController *sectionController = [self.delegate listAdapter:listAdapter sectionControllerForObject:object];
    return (IGListSectionController *)sectionController;
}
- (nullable UIView *)emptyViewForListAdapter:(IGListAdapter *)listAdapter {
    return [self.delegate emptyViewForListAdapter:listAdapter];
}

#pragma mark - ListCoordinatorDelegate
- (void)reloadAllSection {
    [self.adapter reloadObjects:self.adapter.objects];
}
- (void)reloadSectionController:(CommonSectionController *)sectionController {
    CommonSectionAdapter *sectionAdapter = [self.adapter objectAtSection:sectionController.section];
    [self.adapter reloadObjects:@[sectionAdapter]];
}
- (void)reloadSectionAdapters:(NSArray <CommonSectionAdapter *> *)sectionAdapters {
    [self.adapter reloadObjects:sectionAdapters];
}
- (void)reloadSection:(NSInteger)section {
    CommonSectionAdapter *sectionAdapter = [self.adapter objectAtSection:section];
    [self.adapter reloadObjects:@[sectionAdapter]];
}
- (void)reloadSectionAdapter:(CommonSectionAdapter *)sectionAdapter {
    [self.adapter reloadObjects:@[sectionAdapter]];
}
- (void)resetData {
    [self.adapter reloadDataWithCompletion:nil];
}

@end
